﻿using CoachingOrganizer.Logic.Models.Common;
using CoachingOrganizer.Toolkit.Collections.Helpers;
using CoachingOrganizer.WinPhone.Common;
using CoachingOrganizer.WinPhone.UITools;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.ApplicationModel.Resources;
using Windows.UI.Popups;

namespace CoachingOrganizer.WinPhone.ViewModels
{
    public class InteractionViewModel : ViewModelBase
    {
        private readonly InteractionModel _model;
        private ObservableCollection<PeriodViewModel> _periods;

        public ObservableCollection<PeriodViewModel> Periods
        {
            get { return _periods; }
        }

        public ICommand AddNewPeriodCommand
        {
            get { return GetCommand(() => AddNewPeriodCommand, () => _model.AddNewPeriod()); }
        }

        public InteractionViewModel()
        {
            _model = new InteractionModel(new WinPhoneLogicExtender());
            _model.PeriodsChanged += Model_PeriodsChanged;
            _model.PeriodsCollectionChanged += Model_PeriodsCollectionChanged;
            InitModel();
        }

        private async void InitModel()
        {
            using (CancellationTokenSource cancellation = new CancellationTokenSource())
                await _model.LoadPeriodsAsync(cancellation.Token);
        }

        private async void NotifyLoadFailed()
        {
            MessageDialog dialog = new MessageDialog(ResourceLoader.GetForCurrentView().GetString(""));
            await dialog.ShowAsync();
        }

        private void Model_PeriodsChanged(object sender, EventArgs e)
        {
            IEnumerable<PeriodModel> periods = _model.Periods;
            BeginInvokeInUIThread(() =>
            {
                _periods = periods == null ? null : new ObservableCollection<PeriodViewModel>(periods.Select(m => new PeriodViewModel(m)));
                OnPropertyChanged(() => Periods);
            });
        }

        private void Model_PeriodsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            BeginInvokeInUIThread(() => ObservableCollectionHelper.ApplyChangesByNumbers<PeriodModel, PeriodViewModel>(e, _periods, m => new PeriodViewModel(m)));
        }
    }
}
